package org.jeecg.modules.operations.assistant.wechat.service;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.h5.H5Service;
import com.wechat.pay.java.service.payments.jsapi.JsapiService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest;
import com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;
/** Native 支付下单为例 */
public class QuickStart {
    /** 商户号 */
    public static String merchantId = "1700149446";
    /** 商户API私钥路径 */
    public static String privateKeyPath = "/www/wwwroot/fagui/boot/apiclient_key.pem";
    /** 商户API私钥路径 */
    public static String privateKeyPathWin = "C:/software/wechat_pay/1700149446_20241129_cert/apiclient_key.pem";
    /** 商户证书序列号 */
    public static String merchantSerialNumber = "6A7B420DDBEAD8F12754878EA91A53C10CA9406B";
    /** 商户APIV3密钥 */
    public static String apiV3key = "7f897e4c2a8a6a4b719b4b0a617641aa";
    public static void main(String[] args) {

        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
//        System.out.println(scanCodePay(100,"dfsfdsfds","https://shxt.gzxcbd.cn","9999999"));
        try {
            Transaction transaction = QuickStart.queryOrderByOutTradeNo("20241231164726119");
            String tradeState = transaction.getTradeState().name();
            System.out.println(tradeState+"="+transaction.getTradeStateDesc());
        }catch (ServiceException e){
            System.out.println("00000000000000000000000000："+e.getErrorCode()+":"+e.getErrorMessage());
        }
//        System.out.println(h5Pay(100,"dfsfdsfds","https://shxt.gzxcbd.cn","20241222193250451"));
//        System.out.println(jsapiPay(100,"dfsfdsfds","https://shxt.gzxcbd.cn","20241222193250451","of6je6_rgbR4R_jeKCkB0PinoLhQ"));
    }

    /**
     *
     * @param payAmount 支付金额
     * @param description 商品描述
     * @param notifyUrl  支付成功后的回调地址
     * @param outTradeNo  订单号
     * @return CodeUrl 二维码链接
     */
    public static String scanCodePay(Integer payAmount, String description, String notifyUrl, String outTradeNo) {
        Config config = build();
        // 构建service
        NativePayService service = new NativePayService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(payAmount*100);
        request.setAmount(amount);
        request.setAppid("wx23bf3224159631e6");
        request.setMchid(merchantId);
        request.setDescription(description);
        request.setNotifyUrl(notifyUrl);
        request.setOutTradeNo(outTradeNo);
        // 调用下单方法，得到应答
        PrepayResponse response = service.prepay(request);
        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
        System.out.println(response.getCodeUrl());
        return response.getCodeUrl();
    }

    /**
     * 商户订单号查询订单
     *
     * @param outTradeNo  订单号
     * @return 返回交易状态 TRADE_SUCCESS‌：交易成功。
     * TRADE_CLOSED‌：交易关闭。
     * USER_PAYING‌：用户支付中。
     * PAY_ERROR‌：支付失败。
     * NOTPAY‌：未支付。
     * REFUND‌：退款。
     * REVERSE‌：撤销（退款）。
     * USER_CANCEL‌：用户取消。
     * SYSTEMERROR‌：系统错误。
     * UNKNOWN‌：未知状态‌
     */
    public static Transaction queryOrderByOutTradeNo(String outTradeNo) throws ServiceException {
        Config config = build();
        // 构建service
        NativePayService service = new NativePayService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
        request.setMchid(merchantId);
        request.setOutTradeNo(outTradeNo);
        // 调用下单方法，得到应答
        return service.queryOrderByOutTradeNo(request);
    }

    private static Config build(){
        String osName = System.getProperty("os.name").toLowerCase();
        String keyPath = privateKeyPath;
        if (osName.contains("win")) {
            System.out.println("Running on Windows");
            keyPath=privateKeyPathWin;
        }
        /*else if (osName.contains("mac")) {
            System.out.println("Running on Mac OS");
        } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("aix")) {
            System.out.println("Running on Unix/Linux");
        } else {
            System.out.println("Running on an unidentified OS");
        }*/
        // 使用自动更新平台证书的RSA配置
        // 建议将 config 作为单例或全局静态对象，避免重复的下载浪费系统资源
        return new RSAAutoCertificateConfig.Builder()
                        .merchantId(merchantId)
                        .privateKeyFromPath(keyPath)
                        .merchantSerialNumber(merchantSerialNumber)
                        .apiV3Key(apiV3key)
                        .build();
    }

    /**
     *
     * @param payAmount 支付金额
     * @param description 商品描述
     * @param notifyUrl  支付成功后的回调地址
     * @param outTradeNo  订单号
     * @return CodeUrl 二维码链接
     */
    public static String h5Pay(Integer payAmount, String description, String notifyUrl, String outTradeNo) {
        Config config = build();
        // 构建service
        H5Service service = new H5Service.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        com.wechat.pay.java.service.payments.h5.model.PrepayRequest request = new com.wechat.pay.java.service.payments.h5.model.PrepayRequest();
        com.wechat.pay.java.service.payments.h5.model.Amount amount = new com.wechat.pay.java.service.payments.h5.model.Amount();
        amount.setTotal(payAmount*100);
        request.setAmount(amount);
        request.setAppid("wx23bf3224159631e6");
        request.setMchid(merchantId);
        request.setDescription(description);
        request.setNotifyUrl(notifyUrl);
        request.setOutTradeNo(outTradeNo);
        /**这里是场景信息，有时候会出校验失败的问题，这里为了测试流通就加上了，本不是必填字段*/
        com.wechat.pay.java.service.payments.h5.model.SceneInfo sceneInfo = new com.wechat.pay.java.service.payments.h5.model.SceneInfo();
        //这里是客户端的IP
        sceneInfo.setPayerClientIp("14.23.150.211 ");
        request.setSceneInfo(sceneInfo);
        // 调用下单方法，得到应答
        com.wechat.pay.java.service.payments.h5.model.PrepayResponse response = service.prepay(request);
        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
        System.out.println(response.getH5Url());
        return response.getH5Url();
    }

    /**
     *
     * @param payAmount 支付金额
     * @param description 商品描述
     * @param notifyUrl  支付成功后的回调地址
     * @param outTradeNo  订单号
     * @return CodeUrl 二维码链接
     */
    public static String jsapiPay(Integer payAmount, String description, String notifyUrl, String outTradeNo,String openId) {
        Config config = build();
        // 构建service
        JsapiService service = new JsapiService.Builder().config(config).build();
        // request.setXxx(val)设置所需参数，具体参数可见Request定义
        com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest request = new com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest();
        com.wechat.pay.java.service.payments.jsapi.model.Amount amount = new com.wechat.pay.java.service.payments.jsapi.model.Amount();
        amount.setTotal(payAmount*100);
        request.setAmount(amount);
        request.setAppid("wx23bf3224159631e6");
        request.setMchid(merchantId);
        request.setDescription(description);
        request.setNotifyUrl(notifyUrl);
        request.setOutTradeNo(outTradeNo);
        /**这里是场景信息，有时候会出校验失败的问题，这里为了测试流通就加上了，本不是必填字段*/
        com.wechat.pay.java.service.payments.jsapi.model.SceneInfo sceneInfo = new com.wechat.pay.java.service.payments.jsapi.model.SceneInfo();
        //这里是客户端的IP
        sceneInfo.setPayerClientIp("14.23.150.211 ");
//        request.setSceneInfo(sceneInfo);
        com.wechat.pay.java.service.payments.jsapi.model.Payer payer = new com.wechat.pay.java.service.payments.jsapi.model.Payer();
        payer.setOpenid(openId);
        request.setPayer(payer);
        // 调用下单方法，得到应答
        com.wechat.pay.java.service.payments.jsapi.model.PrepayResponse response = service.prepay(request);
        // 使用微信扫描 code_url 对应的二维码，即可体验Native支付
        System.out.println(response.getPrepayId());
        return response.getPrepayId();
    }
}
